package com.powernode.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.SysMenu;
import com.powernode.model.LoginUserDetails;
import com.powernode.service.SysMenuService;
import com.powernode.mapper.SysMenuMapper;
import com.powernode.utils.AuthUtils;
import com.powernode.vo.MenuAndAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 92480
* @description 针对表【sys_menu(菜单管理)】的数据库操作Service实现
* @createDate 2024-07-09 13:58:09
*/
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu>
    implements SysMenuService{

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public MenuAndAuth getMenuAndAuth() {
        //查询用户id
        Long loginedUserId = AuthUtils.getLoginedUserId();
        //查询用户菜单
        Set<SysMenu> menus = sysMenuMapper.getMenu(loginedUserId);
        Set<SysMenu> menuTree = menusTransforTree(menus,0L);
        //查询权限
        LoginUserDetails loginedUserDetails = AuthUtils.getLoginedUserDetails();
        Set<String> permissions = loginedUserDetails.getPermissions();
        MenuAndAuth menuAndAuth = new MenuAndAuth(menuTree, permissions);
        return menuAndAuth;
    }

    private Set<SysMenu> menusTransforTree(Set<SysMenu> menus, long pid) {
        Set<SysMenu> roots = menus.stream().filter(menu -> menu.getParentId() == pid).collect(Collectors.toSet());
        roots.stream().forEach(root ->{
            root.setChild(menusTransforTree(menus,root.getMenuId()));
        });
        return roots;
    }
}




